import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import {
  Form,
  Input,
  Tree
} from 'antd'
import {menulist} from '../../../assets/data/menulist'
const Item = Form.Item

// const { TreeNode } = Tree;

export default class AuthForm extends PureComponent {
  static propTypes = {
    role: PropTypes.object
  }

  constructor (props) {
    // console.log("constructor");
    super(props);

    // 根据传入角色的menus生成初始状态
    const {menus} = this.props.role;
    this.state = {
      checkedKeys: menus,
    };
    
    this.treeNodes = [{key:"all",title:"平台权限",children:menulist}];
    this.authTreeRef=React.createRef();
  }

  /*
  为父组件提交获取最新menus数据的方法
   */
  getMenus = () => this.state.checkedKeys

  /* getTreeNodes = (menuList) => {
    return menuList.reduce((pre, item) => {
      pre.push(
        <TreeNode title={item.title} key={item.key}>
          {item.children ? this.getTreeNodes(item.children) : null}
        </TreeNode>
      )
      return pre
    }, [])
  } */

  // 选中某个node时的回调
  onCheck = checkedKeys => {
    // console.log('onCheck', checkedKeys,this.authTreeRef);
    this.setState({checkedKeys});
  };

  /* componentDidMount () {
  } */

  // 根据新传入的role来更新checkedKeys状态
  /*
  当组件接收到新的属性时自动调用
   */
  /* static getDerivedStateFromProps(props, state) {
    console.log('props, state: ', props, state);
    const menus = props.role.menus;
    state.checkedKeys=["/user"];
    // Return null to indicate no change to state.
    return null;
  } */

  render() {
    // console.log('AuthForm render()')
    const {role} = this.props;
    const {checkedKeys} = this.state;
    // 指定Item布局的配置对象
    const formItemLayout = {
      labelCol: { span: 4 },  // 左侧label的宽度
      wrapperCol: { span: 15 }, // 右侧包裹的宽度
    }

    return (
      <div>
        <Item label='角色名称' {...formItemLayout}>
          <Input value={role.name} disabled/>
        </Item>

        <Tree
          ref={this.authTreeRef}
          checkable
          defaultExpandAll={true}
          checkedKeys={checkedKeys}
          onCheck={this.onCheck}
          treeData={this.treeNodes}
        >
          {/* <TreeNode title="平台权限" key="all">
          </TreeNode> */}
        </Tree>
      </div>
    )
  }
}
